import jwt from "jsonwebtoken";
import { JWT_SECRET } from "../configs/yz";
import { createId } from "../helpers/id-creater";
import { User } from "../types/User";

export const usersTable = {
	users: [
		{ userId: 10000001, username: "aaa" },
		{ userId: 10000002, username: "bbb" },
	] as User[],
	register(params: { username: string; password: string }) {
		const user = { userId: createId(), username: params.username };
		this.users.push(user);
	},
	getUser(userId: number) {
		return this.users.find((user) => user.userId === userId) || null;
	},
	login(username: string) {
		try {
			const user = this.users.find((v) => v.username == username);
			if (!user) throw new Error();
			const token = jwt.sign(user.userId.toString(), JWT_SECRET);
			return token;
		} catch (error) {
			return null;
		}
	},
};
